import {
  deleteMedia,
  fetchLabelOptions,
  fetchMediaList,
  getMediaById,
  unboundMedia
} from "@/api/service/lcd-device/lcd-device";
import { Media } from "@/api/service/lcd-device/types";
import { queryModel } from "@/api/service/model/model";
import { listTheme } from "@/api/service/theme/theme";
import { getUserProfile } from "@/api/service/user";
import { deviceMode, dispatchParams, showDispatch } from "../../device/form";
import { form as tagFrom } from "../../priceTag/data/form";
import {
  canvasConfig,
  currentGroup,
  groupIndex,
  previewToggle,
  selectedProductIds
} from "../dispatch/data/data";
import { dispatchModal, form, resetForm, showForm } from "./form";
import { keys, labelOptions, librarySizeOptions, query, table } from "./table";

export const list = async () => {
  table.value.loading = true;
  const data = await fetchMediaList(query.value);
  table.value.data = data.rows?.map((e: Media) => {
    let label = e.label as string;
    if (label) {
      e.label = label.split(",");
    }
    return e;
  });
  query.value.total = data.total;
  table.value.loading = false;
};

export const edit = async (id?: string) => {
  const targetId = id || keys.value[0];
  const data = await getMediaById(targetId);
  form.value = data.data;
  showForm.value = true;
};
export const create = async () => {
  resetForm();
  showForm.value = true;
};
export const del = async (id?: string) => {
  const ids = id ? [id] : keys.value;
  await deleteMedia(ids);
  await list();
  keys.value = [];
};

export const getTagSize = async () => {
  if (librarySizeOptions.value.length === 0) {
    const data = await queryModel();
    librarySizeOptions.value = data.data.map((e) => {
      return {
        label: e.description,
        value: e.id
      };
    });
  }
};

export const dispatch = async (record: Media) => {
  form.value = record;
  showForm.value = false;

  const setOldVersion = () => {
    showDispatch.value = true;
    deviceMode.value = "lcd";

    tagFrom.value.tagId = record.mediaId;
    tagFrom.value.resolutionId = record.resolutionId;
    tagFrom.value.goodsList = record.goodsList;
    tagFrom.value.templateId = record.templateId!;
    dispatchParams.value.goodsList = record.goodsList;
    if (!dispatchParams.value.goodsList) {
      dispatchParams.value.selectedGoods = [];
      dispatchParams.value.goodsList = [
        {
          label: "a",
          value: ""
        }
      ];
    } else {
      const productItem = dispatchParams.value.goodsList[0];
      if (!productItem) return;
      dispatchParams.value.selectedGoods = [productItem.value];
    }
  };

  if (!record.fwVersion) {
    setOldVersion();
    return;
  }

  const version = Number(record.fwVersion.split(".").join(""));

  if (version < 130) {
    setOldVersion();
    return;
  }

  const { templateId } = form.value;
  try {
    const { data: mediaData } = await getMediaById(record.mediaId);

    let targetGroupId = "";
    if (templateId) {
      targetGroupId = templateId;
    } else {
      /* 处理未绑定模版的逻辑 */
      const { data } = await getUserProfile();
      const { groupsId } = data;
      targetGroupId = groupsId;
    }
    /* 处理已绑定模版的逻辑 */
    const data = await listTheme({
      groupsId: targetGroupId,
      queryType: "0"
    });

    const targetGroup = data.rows[0];

    if (targetGroup) {
      const index = mediaData.ref?.length || 0;
      currentGroup.value = targetGroup;
      canvasConfig.value = targetGroup.items[index];
      groupIndex.value = index;
      mediaData.ref?.forEach(async (e: any) => {
        const goodsId = e.value;
        selectedProductIds.value.push(goodsId);
      });
      previewToggle.value += 1;
    }
    dispatchModal.value = true;
  } catch (error) {
    // error
  }
};

export const unbound = async (id: string) => {
  await unboundMedia(id);
  list();
};

// export const getResolution = async () => {
//   const res = await listResolution();
//   resolutionList.value = res.rows.map((item: IResolution) => {
//     return {
//       value: item.resolutionId,
//       label: item.description
//     };
//   });
// };

export const getLabelOptions = async () => {
  const data = await fetchLabelOptions(true);
  const group: any[] = [];
  data.data.forEach((e: any) => {
    e.label.split(",").forEach((v: string) => {
      group.push({
        label: v,
        value: v
      });
    });
  });

  labelOptions.value = group;
};
